package com.sway.data.pool;

import com.sway.data.core.SwayDataSource;

import java.lang.reflect.Proxy;
import java.sql.Connection;


public class ConnectionPool implements IPool{

    private ConnectionHolder connectionHolder;
    private ThreadLocal<Connection> currentConnection = new ThreadLocal<>();

    public ThreadLocal<Connection> getCurrentConnection() {
        return this.currentConnection;
    }

    public ConnectionPool(SwayDataSource dataSource, ConnectionHolder connectionHolder){
        this.connectionHolder = connectionHolder;
        this.connectionHolder.init(dataSource);
    }

    @Override
    public synchronized Connection getConnection() {
        Connection currentConn = currentConnection.get();
        if (currentConn != null){
            return currentConn;
        }
        currentConn = this.connectionHolder.pop();
        final Connection conn = currentConn;
        Connection proxyConnection = (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(),conn.getClass().getInterfaces(),
                ( proxy, method, args)->{
                    if (method.getName().equals("close")){
                        if (conn.getAutoCommit()){
                            connectionHolder.push(conn);
                            currentConnection.set(null);
                        }
                        return null;
                    }
                    else {
                        return method.invoke(conn,args);
                    }

                });
        currentConnection.set(proxyConnection);
        return proxyConnection;
    }

    @Override
    public synchronized void close(Connection connection) {
        this.connectionHolder.close(connection);
    }
}
